package ants;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;

import cell.Cell;

import com.google.common.collect.Iterables;

public class Logger {
  
  public static GameState         gameState;
  
  /** This is the name of the directory. */
  private static final String     LOG_FILES = "DiffusionBot_Logs";
  
  public static final PrintWriter logFile   = makePrintWriter(makePathName(LOG_FILES));
  
  
  static {
    logFile.println("\n\n\t\t\tLog of " + getDateString( ) + "\n\n");
  }
  
  
  public static void log(String message) {
    logFile.println(gameState.getLogMessagePrefix( ) + message.toString( ));
    logFile.flush( );
  }
  
  
  public static void logChar(char c) {
    logFile.println(c);
    logFile.flush( );
  }
  
  
  private static String makePathName(String directoryName) {
    final File dir = new File(directoryName);
    if (!dir.exists( )) dir.mkdir( );
    
    final String dateString = getDateString( );
    
    return dir + "\\" + dateString + ".txt";
  }
  
  
  private static String getDateString( ) {
    final Date date = Calendar.getInstance( ).getTime( );
    final String dateString = date.toString( ).substring(4, 19).replace(':', '-');
    return dateString;
  }
  
  
  private static PrintWriter makePrintWriter(String fileName) {
    PrintWriter out = null;
    try {
      out = new PrintWriter(new FileWriter(fileName, false), true);
    } catch (final IOException e) {
      e.printStackTrace( );
      System.exit(-1);
    }
    return out;
  }
  
  
  /**
   * Same as mapLocations.toString( ) except that what is called on each element
   * is toString(gameState), which prints the cellProperties.
   * 
   * @param mapLocations
   *          an Iterable of MapLocation_s
   * @return the string representation of mapLocations as a list
   */
  public static String toString(Iterable<Cell> mapLocations) {
    if (Iterables.size(mapLocations) == 0) return "[ ]";
    
    final StringBuilder sb = new StringBuilder("[");
    sb.append(Iterables.get(mapLocations, 0).toString(gameState));
    for (final Cell cell: Iterables.skip(mapLocations, 1)) {
      sb.append(", ");
      sb.append(cell.toString(gameState));
    }
    sb.append("]");
    return sb.toString( );
  }
  
  
}
